<template>
  <div class="doctor-container">
    <!-- 科室分类区域 -->
    <div class="dept-container">
      <h2 class="section-title">科室导航</h2>
      <div class="first-dept-grid">
        <!-- 一级分类 -->
        <div
          class="first-dept-card"
          v-for="(firstDept, firstIndex) in firstDepartments"
          :key="firstIndex"
        >
          <div
            class="first-dept-title"
            @click="toggleSecondDept(firstIndex)"
          >
            <span class="dept-name">{{ firstDept.name }}</span>
            <i class="el-icon-arrow-down arrow-icon" :class="{ 'rotate': firstDept.expand }"></i>
          </div>

          <!-- 二级分类（展开/收起） -->
          <transition name="slide-fade">
            <div
              class="second-dept-wrap"
              v-show="firstDept.expand"
            >
              <div class="second-dept-tags">
                <el-tag
                  v-for="(secondDept, secondIndex) in firstDept.children"
                  :key="secondIndex"
                  :type="activeDept === secondDept ? 'danger' : 'info'"
                  @click="handleDeptClick(secondDept)"
                  effect="plain"
                  class="second-dept-tag"
                >
                  {{ secondDept }}
                </el-tag>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>

    <!-- 医生列表区域 -->
    <div class="doctor-section">
      <h2 class="section-title">
        {{ activeDept ? `${activeDept} 医生` : '全部医生' }}
        <span class="doctor-count">({{ filteredDoctors.length }}人)</span>
      </h2>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-state">
        <el-skeleton animated>
          <template #template>
            <div class="skeleton-card" v-for="i in 4" :key="i">
              <el-skeleton-item variant="image" class="skeleton-avatar" />
              <el-skeleton-item variant="text" class="skeleton-text short" />
              <el-skeleton-item variant="text" class="skeleton-text long" />
              <el-skeleton-item variant="text" class="skeleton-text short" />
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 医生卡片 -->
      <div v-else-if="filteredDoctors.length > 0" class="doctor-grid">
        <el-card
          v-for="(doctor, index) in filteredDoctors"
          :key="index"
          shadow="hover"
          class="doctor-card"
        >
          <div class="doctor-card-content">
            <div class="doctor-header">
              <div class="avatar-placeholder">
                <i class="el-icon-user-solid"></i>
              </div>
              <div class="doctor-basic-info">
                <h3 class="doctor-name">{{ doctor.name }}</h3>
                <p class="doctor-title">{{ doctor.title }}</p>
                <el-tag type="success" size="mini" class="dept-tag">{{ doctor.dept }}</el-tag>
              </div>
            </div>

            <div class="doctor-details">
              <div class="info-row">
                <i class="el-icon-star-off info-icon"></i>
                <span class="info-label">专长:</span>
                <span class="info-value">{{ doctor.specialty }}</span>
              </div>

              <div class="info-row">
                <i class="el-icon-time info-icon"></i>
                <span class="info-label">出诊:</span>
                <span class="info-value schedule">{{ doctor.time }}</span>
              </div>

              <div class="info-row">
                <i class="el-icon-phone-outline info-icon"></i>
                <span class="info-label">电话:</span>
                <span class="info-value">{{ doctor.contact }}</span>
              </div>
            </div>

            <div class="card-actions">
              <el-button type="primary" size="small" @click="goToReservation(doctor)">预约挂号</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 无数据提示 -->
      <div v-else class="empty-state">
        <div class="empty-icon">
          <i class="el-icon-office-building"></i>
        </div>
        <p class="empty-text">暂无相关医生信息</p>
        <el-button @click="showAllDoctorsHandler" type="primary" size="big">查看全部医生</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';
export default {
  name: 'DoctorFilter',
  data() {
    return {
      // 一级科室+二级科室（原生功能保留）
      firstDepartments: [
        { name: '内科', expand: false, children: ['呼吸内科', '消化内科', '神经内科', '心血管内科', '肾内科', '血液内科', '免疫科', '内分泌科'] },
        { name: '外科', expand: false, children: ['普通外科', '神经外科', '心胸外科', '泌尿外科', '心血管外科', '乳腺外科', '肝胆外科', '器官移植', '肛肠外科', '烧伤科', '骨外科'] },
        { name: '妇产科', expand: false, children: ['妇科', '产科', '计划生育', '妇幼保健'] },
        { name: '男科', expand: false, children: ['前列腺专科', '男性生殖健康'] },
        { name: '儿科', expand: false, children: ['儿科综合', '小儿内科', '小儿外科', '新生儿科', '儿童营养保健科'] },
        { name: '五官科', expand: false, children: ['耳鼻喉科', '眼科', '口腔科'] },
        { name: '肿瘤科', expand: false, children: ['肿瘤内科', '肿瘤外科', '肿瘤妇科', '骨肿瘤科', '放疗科', '肿瘤康复科', '肿瘤综合科'] },
        { name: '皮肤性病科', expand: false, children: ['皮肤科', '性病科'] },
        { name: '中医科', expand: false, children: ['中医全科', '中医内科', '中医外科', '中医妇科', '中医儿科', '中医保健科', '针灸按摩科', '中医骨伤科', '中医肿瘤科'] },
        { name: '传染科', expand: false, children: ['肝病科', '艾滋病科', '结核病', '寄生虫'] },
        { name: '精神心理科', expand: false, children: ['精神科', '心理咨询科'] }
      ],
      activeDept: '', // 选中的二级科室名称
      doctors: [], // 后端返回的原始医生数据
      isLoading: false, // 加载状态（优化用户体验）
      showAllDoctors: true // 是否显示全部医生
    };
  },
  computed: {
    // 核心筛选逻辑：根据选中的二级科室过滤医生
    filteredDoctors() {
      if (!this.activeDept && this.showAllDoctors) return this.doctors; // 未选科室 → 显示所有医生
      // 精准匹配科室名称（与数据库返回的department字段一致）
      return this.doctors.filter(doctor => doctor.dept === this.activeDept);
    }
  },
  created() {
    this.loadAllDoctors(); // 页面初始化加载所有医生
  },
  methods: {
    // 1. 加载所有医生（初始加载用）
    loadAllDoctors() {
      this.isLoading = true;
      request({
        url: '/system/doctor/all',
        method: 'get'
      })
        .then(res => {
          // 核心修复：把 res.data.code → res.code，res.data.data → res.data
          if (res && res.code === 200 && Array.isArray(res.data)) {
            this.doctors = res.data.map(item => ({
              name: item.doctor || '未知医生', // 字段容错：避免null导致页面空白
              dept: item.department || '未知科室', // 数据库department字段直接映射
              title: item.title || '无职称',
              specialty: item.specialty || '暂无专长描述',
              time: item.schedule || '暂无出诊信息',
              contact: item.contact || '暂无联系方式'
            }));
          } else {
            console.error('加载医生失败：后端返回格式异常', res); // 修复：打印完整res，而非res.data
            this.doctors = [];
          }
        })
        .catch(err => {
          console.error('加载医生失败：', err.message);
          this.doctors = [];
        })
        .finally(() => {
          this.isLoading = false; // 无论成功失败，结束加载状态
        });
    },

    // 2. 切换一级科室展开/收起（原生功能）
    toggleSecondDept(index) {
      // 关闭其他一级科室的展开状态（避免多开）
      this.firstDepartments.forEach((dept, i) => {
        if (i !== index) dept.expand = false;
      });
      // 切换当前一级科室的展开/收起
      this.firstDepartments[index].expand = !this.firstDepartments[index].expand;
    },

    // 3. 点击二级科室筛选医生（核心功能）
    handleDeptClick(deptName) {
      // 切换选中状态（再次点击取消选中）
      this.activeDept = this.activeDept === deptName ? '' : deptName;
      this.showAllDoctors = false;

      // 取消选中 → 重新加载所有医生
      if (!this.activeDept) {
        this.showAllDoctors = true;
        this.loadAllDoctors();
        return;
      }

      // 选中科室 → 调用后端筛选接口
      this.isLoading = true;
      request({
        url: `/system/doctor/dept/${encodeURIComponent(deptName)}`,
        method: 'get',
        params: { department: deptName } // 冗余传参，确保后端能接收
      })
        .then(res => {
          // 核心修复：把 res.data.code → res.code，res.data.data → res.data
          if (res && res.code === 200 && Array.isArray(res.data)) {
            this.doctors = res.data.map(item => ({
              name: item.doctor || '未知医生',
              dept: item.department || '未知科室',
              title: item.title || '无职称',
              specialty: item.specialty || '暂无专长描述',
              time: item.schedule || '暂无出诊信息',
              contact: item.contact || '暂无联系方式'
            }));
          } else {
            console.error(`筛选${deptName}医生失败：返回格式异常`, res); // 修复：打印完整res，而非res.data
            this.doctors = [];
          }
        })
        .catch(err => {
          console.error(`筛选${deptName}医生失败：`, err.message);
          this.doctors = [];
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // 显示全部医生处理函数
    showAllDoctorsHandler() {
      this.activeDept = '';
      this.showAllDoctors = true;
      this.loadAllDoctors();
    },

    // 跳转到预约挂号页面
    goToReservation(doctor) {
      // 使用路径跳转而不是路由名称，避免路由未定义错误
      this.$router.push('/reservation');
    }
  }
};
</script>

<style scoped>
.doctor-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.doctor-count {
  font-size: 16px;
  color: #909399;
  font-weight: normal;
}

/* 科室分类容器 */
.dept-container {
  margin-bottom: 30px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.first-dept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.first-dept-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.first-dept-card:hover {
  box-shadow: 0 4px 16px 0 rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.first-dept-title {
  padding: 15px 20px;
  background: #f5f7fa;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  transition: background 0.2s;
}

.first-dept-title:hover {
  background: #ecf5ff;
}

.dept-name {
  font-size: 16px;
  color: #303133;
}

.arrow-icon {
  transition: transform 0.3s ease;
  font-size: 18px;
  color: #909399;
}

.rotate {
  transform: rotate(180deg);
}

.second-dept-wrap {
  padding: 15px 20px;
  background: white;
}

.second-dept-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.second-dept-tag {
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 20px;
  font-size: 14px;
}

.second-dept-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 医生列表区域 */
.doctor-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.doctor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.doctor-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.doctor-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.doctor-card-content {
  padding: 20px;
}

.doctor-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #64b5f6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36px;
  margin-right: 20px;
}

.doctor-basic-info {
  flex: 1;
}

.doctor-name {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.doctor-title {
  font-size: 16px;
  color: #606266;
  margin: 0 0 10px 0;
}

.dept-tag {
  font-size: 12px;
}

.doctor-details {
  margin-bottom: 25px;
}

.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.info-icon {
  font-size: 18px;
  color: #409eff;
  margin-right: 10px;
  margin-top: 2px;
}

.info-label {
  font-weight: 500;
  color: #606266;
  width: 60px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  line-height: 1.5;
  flex: 1;
  font-size: 14px;
}

.schedule {
  color: #e6a23c;
  font-weight: 500;
}

.card-actions {
  display: flex;
  justify-content: center;
}

.card-actions .el-button {
  flex: 1;
  margin: 0 5px;
  width: 100%;
  height:30px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #c0c4cc;
}

.empty-text {
  font-size: 18px;
  margin-bottom: 20px;
}

/* 加载状态样式 */
.loading-state {
  padding: 20px 0;
}

.skeleton-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.skeleton-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 20px;
}

.skeleton-text {
  margin-bottom: 15px;
}

.short {
  width: 60%;
}

.long {
  width: 100%;
}

/* 动画效果 */
.slide-fade-enter-active {
  transition: all 0.3s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@media (max-width: 768px) {
  .doctor-container {
    padding: 15px;
  }

  .first-dept-grid {
    grid-template-columns: 1fr;
  }

  .doctor-grid {
    grid-template-columns: 1fr;
  }

  .doctor-header {
    flex-direction: column;
    text-align: center;
  }

  .avatar-placeholder {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .card-actions {
    flex-direction: column;
  }

  .card-actions .el-button {
    margin: 5px 0;
  }
}
</style>